package com.sl.au.service.impl;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

import com.sl.au.entity.Attachment;
import com.sl.au.entity.StorageProperties;
import com.sl.au.repository.AttachmentRepository;
import com.sl.au.service.StorageException;
import com.sl.au.service.StorageFileNotFoundException;

@Service("attachmentService")
@Transactional
public class AttachmentServiceImpl extends BaseServiceImpl implements com.sl.au.service.AttachmentService {
	private static Logger logger = LoggerFactory.getLogger(AttachmentServiceImpl.class);
	private final Path rootLocation;
	private final Long K = 1024l, M = K * 1024l, G = M * 1024l;
	@Autowired
	AttachmentRepository attachmentRepository;

	@Autowired
	public AttachmentServiceImpl(StorageProperties properties) {
		this.rootLocation = Paths.get(properties.getLocation());
	}

	@Override
	public void init() {
		try {
			if (!Files.exists(rootLocation))
				Files.createDirectory(rootLocation);
		} catch (IOException e) {
			// throw new StorageException("无法创建附件根目录", e);
			logger.error("无法创建附件根目录");
		}

	}

	@Override
	public void save(MultipartFile file, String sender, String parentId, String groupId) {
		if (null == file)
			return;
		String fileName = file.getOriginalFilename();
		try {
			if (file.isEmpty()) {
				throw new StorageException("无法存储空文件" + fileName);
			}

			String savedFileName = java.util.UUID.randomUUID().toString();

			   if(groupId.equals("avatar")){//用户头像
				   savedFileName=parentId;
					try {
						this.attachmentRepository.deleteByParentIdAndGroupId(parentId, "avatar");
						Files.deleteIfExists(this.load(savedFileName));
					} catch (IOException e) {
						this.logger.error(e.getMessage());
					}
			   }
		
			Files.copy(file.getInputStream(), this.rootLocation.resolve(savedFileName));
			// 文件传后将文件信息记录入录
			Attachment a = new Attachment();

			Long size = 0l;
			Double convertedSize = 0d;
			String unit = "";
			size = file.getSize();
			if (size < K) {
				unit = "B";
				convertedSize = new Double(size);
			} else if (size < M) {
				unit = "K";
				convertedSize = size / (K * 1.0);
			} else if (size < G) {
				unit = "M";
				convertedSize = size / (M * 1.0);
			} else {
				unit = "G";
				convertedSize = size / (G * 1.0);
			}

			a.setFileSize(new BigDecimal(convertedSize).setScale(2, BigDecimal.ROUND_UP).doubleValue());
			a.setSizeUnit(unit);
			a.setSender(sender);
			a.setOriginalFileName(fileName);
			a.setSavedFileName(savedFileName);
			a.setParentId(parentId);
			a.setGroupId(groupId);
			a.setUploadDate(new Date());
			this.attachmentRepository.saveAndFlush(a);

		} catch (IOException e) {
			throw new StorageException("存储附件失败" + file.getOriginalFilename(), e);
		}

	}

	@Override
	public Path load(String filename) {

		return rootLocation.resolve(filename);
	}

	@Override
	public Resource loadAsResource(String filename) {
		try {
			Path file = load(filename);

			if (null == file || !Files.exists(file))
				throw new StorageFileNotFoundException("找不到文件: " + filename);
			Resource resource = new UrlResource(file.toUri());
			if (resource.exists() || resource.isReadable()) {
				return resource;
			} else {
				throw new StorageFileNotFoundException("找不到文件: " + filename);

			}
		} catch (MalformedURLException e) {
			throw new StorageFileNotFoundException("无法读取文件: " + filename, e);
		}
	}

	@Override
	public void deleteAll(String parentId, String groupId) {

	}

	@Override
	public AttachmentRepository getRepository() {
		return this.attachmentRepository;
	}

	@Override
	public List<Attachment> getByParentId(String parentId, String groupId) {
		return this.attachmentRepository.findByParentIdAndGroupId(parentId, groupId);
	}

	@Override
	public void deleteA(String id) {

		Attachment a = this.attachmentRepository.getOne(id);
		if (null != a) {
			String name = a.getSavedFileName();
			this.attachmentRepository.delete(a);
			this.attachmentRepository.flush();
			// remove a file from disk
			try {
				Files.deleteIfExists(this.load(name));
			} catch (IOException e) {
				this.logger.error(e.getMessage());
			}
		}

	}

	@SuppressWarnings("finally")
	@Override
	public String upload(MultipartFile file) {
		if (null == file)
			return null;
		String savedFileName = null;
		String fileName = file.getOriginalFilename();
		try {
			if (file.isEmpty()) {
				throw new StorageException("无法存储空文件" + fileName);
			}
			savedFileName = java.util.UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
			Path path = this.rootLocation.resolve(savedFileName);
			Files.copy(file.getInputStream(), path);

		} catch (IOException e) {
			throw new StorageException("存储附件失败" + file.getOriginalFilename(), e);
		} finally {
			return savedFileName;
		}

	}
	
	 public File getUniqueNameFile(String parentDir, final String fileId)
	    {
	        File dir = new File(parentDir);
	        if(null==dir) return null;
	        FileFilter fileFilter = new FileFilter()
	        {
	            public boolean accept(File file)
	            {
	                return file.getName().contains(fileId);
	            }
	        };
	        File[] files = dir.listFiles(fileFilter);
	        if(null==files)
	        	return null;
	        else{
	        	return files[0];
	        }
	    }

}
